<template>
  <div>
    <auth-tag ref="authTagRef" code="role:listManager" tips="无权限访问" :popup="true">
      <main-layout>
        <template v-slot:top>
          <el-form ref="searchForm" :inline="true" :model="searchInfo">
            <el-form-item label="ID">
              <el-input v-model="searchInfo.roleId" placeholder="ID" clearable />
            </el-form-item>
            <el-form-item label="角色名称">
              <el-input v-model="searchInfo.roleName" placeholder="用户名" clearable />
            </el-form-item>

            <el-form-item>
              <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
              <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
            </el-form-item>
          </el-form>
        </template>

        <auth-tag code="role:insert">
          <div class="gva-btn-list">
            <el-button size="small" type="primary" icon="plus" @click="openAdd">新增角色</el-button>
          </div>
        </auth-tag>

        <c-table :page="{ pageSize, pageIndex, total }" :lists="tableData" @current-change="handleCurrentChange"
          @size-change="handleSizeChange">
          <el-table-column align="center" label="ID" min-width="150" prop="roleId" />
          <el-table-column align="center" label="角色名称" min-width="120" prop="roleName" />
          <el-table-column align="center" label="角色描述" min-width="110" prop="remark" />
          <el-table-column align="center" label="用户数" min-width="120" prop="userNumber" />
          <el-table-column align="center" label="操作人" min-width="120" prop="updateUserName" />
          <el-table-column align="center" label="操作时间" width="160" >
            <template #default="scope">
              {{ formatDateLong(scope.row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" :width="oWidth" fixed="right" v-if="oWidth">
            <template #default="scope">
              <auth-tag code="role:userList">
                <el-button type="text" icon="search" size="small" @click="openRoleUser(scope.row)">查看用户</el-button>
              </auth-tag>
              <auth-tag code="role:get">
                <el-button type="text" icon="search" size="small" @click="openEdit(scope.row,true)">查看</el-button>
              </auth-tag>
              <auth-tag code="role:update">
                <el-button type="text" icon="edit" size="small" @click="openEdit(scope.row)">编辑</el-button>
              </auth-tag>
              <auth-tag code="role:delete">
                <el-button type="text" icon="delete" size="small" @click="del(scope.row)">删除</el-button>
              </auth-tag>
            </template>
          </el-table-column>
        </c-table>

        <add-role v-if="addUserFlag" v-model:show="addUserFlag" :title="editData.islook?'查看详情':(editData.roleId?'编辑角色':'新增角色')" @result="getTableData" :editData="editData"/> 

        <role-users v-if="openUersFlag" v-model:show="openUersFlag" :showBtn="false" :title="`【${editData.roleName}】角色用户列表`" :id="editData.roleId"/>

      </main-layout>
    </auth-tag>
  </div>
</template>

<script setup>

import {getRoleList,delRole} from '@/api/user'

import mainLayout from '@/components/custom/mainLayout.vue'
import cTable from '@/components/custom/cTable.vue'
import addRole from './components/addRole.vue'
import roleUsers from './components/roleUsers.vue'
// import authTag from '@/components/authTag.vue'
import { emitter } from '@/utils/bus.js'

import { nextTick, ref, watch, onActivated } from 'vue'
import { ElMessageBox } from 'element-plus'
import {formatDateLong} from '@/utils/format'

import { useUserStore } from '@/pinia/modules/user'
import {message} from '@/utils/element.js'

const userStore = useUserStore()
onActivated(() => {
  console.log("----onActivated-----",userStore.pageInit)
  if (userStore.pageInit) { // 需要刷新页面
    init()
  } else if (userStore.refreshFn) { // 刷新函数存在，在执行
    userStore.refreshFn()
  }
  //authTagRef.value.init()
})


const pageIndex = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
const addUserFlag = ref(false)
const openUersFlag = ref(false)
const loading = ref(true)
const authTagRef = ref(null)

const init = () => {
  pageIndex.value = 1
  onReset()
  computeOpraterWidth()
  getTableData()
}



const onReset = () => {
  pageIndex.value = 1
  searchInfo.value = {}
}
// 搜索
const onSubmit = () => {
  pageIndex.value = 1
  getTableData()
}
// 分页
const handleSizeChange = (val) => {
  pageIndex.value = 1
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  pageIndex.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  const res = await getRoleList({ page: pageIndex.value, size: pageSize.value, ...searchInfo.value })
  if (res.code === 200) {
    tableData.value = res.data
    total.value = res.total
  }
  if(res.status==403){
    ElMessageBox.confirm('无权访问','提示',
      {
          confirmButtonText: '确定',
          showCancelButton:false,
          type: 'warning',
      }).then(async () => {
        emitter.emit('closeThisPage') // 关闭当前页面
      })
  }
  loading.value = false
}

const openAdd = ()=>{
  editData.value = {}
  addUserFlag.value = true
}

const editData = ref({})
const openEdit = (item,islook)=>{
  editData.value = item
   if(islook){
      editData.value.islook = true
   }else{
      editData.value.islook = false
   }
  addUserFlag.value = true
}

const del = (item)=>{
  ElMessageBox.confirm(
    '确认删除该数据吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
      const res = await delRole(item.roleId)
      if(res.code == 200){
        message('删除成功',2)
        getTableData()
      }else{
        message(res.message,3)
      }
  }).catch(() => {
      
  })
}

const openRoleUser = (item)=>{
  editData.value = item
  openUersFlag.value = true
}

// 计算表格操作栏宽度
const oWidth = ref('60')
const computeOpraterWidth = ()=>{
  let farr = []
  const arr = ['role:userList','role:get','role:update','role:delete']
  const plists = userStore.userInfo.permissionUserList // 权限数组
  for(let i=0;i<arr.length;i++){
    const sitem = arr[i]
    const fitem = plists.find(item =>(item.code && item.code.indexOf(sitem)>-1))
    if(fitem){ 
      farr.push(sitem)
      continue;  
    } 
  }
  const l_width= 70  // 2个文字按钮站占的宽度
  if(farr.indexOf('role:userList')>-1){
    oWidth.value = 90 + (farr.length-1) * l_width
  }else{
    oWidth.value = farr.length * l_width
  }
}

</script>

<style lang="scss" scoped>
.inputLine {
  display: flex;
  width: 200px;
  .zhi{
    padding: 0 10px;
  }
  s{
    font-style: normal;
    text-decoration: none;
    padding: 0 0 0 5px;
    color: var(--el-text-color-regular);
  }
}
</style>
